package com.ebei.admin.common.util;

import com.ebei.admin.common.constant.Constants;
import com.ebei.admin.model.dto.UserInfo;
import com.ebei.admin.model.entity.SysUser;
import com.ebei.admin.service.SysOrgService;
import com.ebei.admin.service.SysRoleService;
import com.ebei.admin.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Component
public final class AuthRealm {

    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysOrgService sysOrgService;

    private static AuthRealm authRealm;

    @PostConstruct
    public void init() {
        authRealm = this;
        authRealm.sysRoleService = this.sysRoleService;
        authRealm.sysUserService = this.sysUserService;
        authRealm.sysOrgService = this.sysOrgService;
    }

    /**
     * 超级管理员判断
     * @return
     */
    public static boolean isSpAdmin() {
        Integer userId = getPrincipal().getUserId();
        return authRealm.sysRoleService.hasPermission(userId, Constants.SUPER_ADMIN);
    }

    /**
     * 政府用户判断
     * @return
     */
    public static boolean isGov() {
        Integer userId = getPrincipal().getUserId();
        SysUser sysUser = authRealm.sysUserService.selectById(userId);
        if (Constants.TYPE_GOV.equals(sysUser.getType())) {
            return true;
        }
        return false;
    }

    /**
     * 企业用户判断
     * @return
     */
    public static boolean isCom() {
        Integer userId = getPrincipal().getUserId();
        SysUser sysUser = authRealm.sysUserService.selectById(userId);
        if (Constants.TYPE_COM.equals(sysUser.getType())) {
            return true;
        }
        return false;
    }

    public static String getLoginLevelNum() {
        SysUser user = getPrincipal();
        if (user != null) {
            return authRealm.sysOrgService.selectById(user.getOrgId()).getLevelNum();
        }
        return null;
    }

    /**
     * 获取登陆人
     * @return
     */
    public static SysUser getPrincipal() {
        HttpServletRequest request = getRequest();
        HttpSession session = request.getSession(false);
        if (session != null) {
            UserInfo userInfo = (UserInfo) session.getAttribute(Constants.LOGIN_INFO);
            SysUser user = userInfo.getSysUser();
            return user;
        }
        return null;
    }

    public static HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

}
